package com.fjzx.androidframe.network.downloader;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;


import com.fjzx.androidframe.network.callback.DownloadProgressListener;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * 带进度的ResponseBody
 *
 * @author xiongyongcong
 */
public class ProgressResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private DownloadProgressListener mListener;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody body, DownloadProgressListener listener) {
        responseBody = body;
        mListener = listener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (mListener != null) {
                mListener.onProgress(msg.arg1, msg.arg2);
            }
        }
    };

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                Message msg = mHandler.obtainMessage();
                msg.arg1 = (int) totalBytesRead;
                msg.arg2 = (int) contentLength();
                mHandler.sendMessage(msg);
                return bytesRead;
            }
        };
    }
}
